using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.HotUpdate;
using IQIGame.USDK;
using System;
using UnityEngine;
using UnityEngine.Networking;

namespace IQIGame.Onigao.GamePlay
{
    public enum LoginMethod
    {
        UserLogin, CreateOrder
    }

    public class LoginWebRequest<R> where R : LoginBaseResponse
    {
        public async UniTask<R> SendRequest(LoginMethod method, LoginRequestBaseData data)
        {
            string subUrl;
            switch (method)
            {
                case LoginMethod.UserLogin:
                    subUrl = "/client/user_login";
                    break;
                case LoginMethod.CreateOrder:
                    subUrl = "/client/create_recharge_order";
                    break;
                default:
                    LogGame.LogError($"LoginWebRequest Unspport LoginMethod = {method}");
                    return null;
            }

            // 创建发送数据
            data.sdkName = ManagerCenter.ProjectSetting.BuildInfo.SDKName;
            data.channelNo = ManagerCenter.ProjectSetting.IsSDKMode() ? IQIUSDK.Instance.getChannelId().ToString() : ManagerCenter.ProjectSetting.BuildInfo.ChannelName;
            data.version = Application.version;
            data.packageName = Application.identifier;
            data.mtype = Application.platform.ToString();
            data.system = SystemInfo.operatingSystem;
            data.systype = SystemInfo.deviceModel;
            data.nettype = Application.internetReachability == NetworkReachability.NotReachable ? "NotReachable" : (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork ? "Mobile" : "WiFi");
            data.mac = DeviceInfoUtil.GetMacAddressFormat();
            data.idfa = "";
            data.assetVersion = PatchLogicContext.CurrResVersion == null ? 0 : PatchLogicContext.CurrResVersion.Revision;

            var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            string dataStr = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(jsonData));
            long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            string sign = MD5Util.CalculateMD5(dataStr + timestamp + "iqigame0423");

            string url = ManagerCenter.ProjectSetting.BuildInfo.LoginUrl + subUrl;
            url += UnityWebRequest.EscapeURL($"?data={dataStr}&sign={sign}&timestamp={timestamp}");
            Debug.Log($"start http request {url}");

            try
            {
                // 创建请求对象
                using (var request = new UnityWebRequest(url, "GET"))
                {
                    //超时
                    request.timeout = 5;
                    request.downloadHandler = new DownloadHandlerBuffer();
                    await request.SendWebRequest();
                    if (request.result != UnityWebRequest.Result.Success || request.responseCode != 200)
                    {
                        LogGame.LogWarning($"Login network error, code: {request.responseCode}");
                        return null;
                    }
                    var response = Newtonsoft.Json.JsonConvert.DeserializeObject<R>(request.downloadHandler.text);
                    if (response == null)
                    {
                        LogGame.LogWarning($"Login failed, body:{request.downloadHandler.text}");
                        return null;
                    }
                    if (response.code != 0)
                    {
                        LogGame.LogWarning($"Login failed, code = {response.code}");
                        return response;
                    }
                    return response;
                }
            }
            catch (UnityWebRequestException e)
            {
                LogGame.LogWarning($"Login network error, {e}");
                return null;
            }
            catch (Exception e)
            {
                LogGame.LogError(e);
                return null;
            }
        }
    }
}
